<template>
  <c-select
    v-bind="$attrs"
    v-on="$listeners"
    v-model="arrayValue"
    :options="cateList"
    @change="handleItemChange"
    :props="props"
    :multiple="true"
  ></c-select>
</template>

<script>
export default {
  components: {},
  props: {
    value: {
      type: String,
      default: '',
    },
  },
  model: {
    prop: 'value',
    event: 'getValue',
  },
  data() {
    return {
      arrayValue: [],
      props: {
        value: 'id',
        label: 'category_name',
      },
    }
  },
  computed: {
    cateList() {
      return this.$store.getters.enumCategory
    },
  },
  watch: {
    value: {
      handler: function (val) {
        this.arrayValue = val ? val?.split(',') : []
      },
      immediate: true,
    },
  },
  created() {
    this.$store.dispatch('getEnumCategory')
  },
  mounted() {},
  methods: {
    handleItemChange(val) {
      let label = ''

      if (val) {
        if (typeof val === 'string') {
          const select = this.cateList.find(item => item.id === val) || {}
          label = select.category_name
        } else {
          const labels = []
          for (let p of val) {
            const select = this.cateList.find(item => item.id === p) || {}
            labels.push(select.category_name || '')
          }
          label = labels.join(',')
        }
      }

      this.$emit('select', label)
      this.$emit('getValue', val?.join(',') ?? '')
    },
  },
}
</script>

<style lang="scss" scoped></style>
